<template>
  <div id="warnDialog">
    <div class="warnMask" v-if="warnList.length"></div>
    <!-- <el-button @click="add">warnAdd</el-button>
    <el-button @click="pauseAudio">stop</el-button> -->
    <audio controls="controls" ref="audioRef" hidden loop autoplay :src="audioSource"></audio>
    <div class="dialogBox">
      <div class="dialog">
        <div
          class="warnBox"
          :class="i ? 'bj2' : 'bj1'"
          :style="{
            '--W': i == 0 ? '6rem' : i < 3 ? `${6 - i * 1}rem` : `4rem`,
            '--T': i == 0 ? '50%' : i < 3 ? `${50 - i * 3}%` : `44%`,
            '--Z': `${100000 - i}`,
          }"
          v-for="(item, i) in warnList"
          :key="item._id"
        >
          <div class="header">
            <div class="text" v-show="i == 0"><div>报警通知</div></div>
            <div class="close">
              <div class="clear" @click="clear" v-if="warnList.length > 1 && i == 0">一键关闭全部弹窗</div>
              <img src="../assets/image/close.png" alt="" @click="close(i)" v-show="i == 0" />
            </div>
          </div>
          <div class="ctn">
            <div class="left">
              <div class="deviceId">
                <div>{{ item?.deviceId }}</div>
              </div>

              <div class="deviceName">
                <div class="name" v-if="item?.device_name">
                  {{ item?.device_name }}
                </div>
                <div>
                  <el-tag
                    :style="{
                      color:
                        item?.level == 9
                          ? '#d1eaff'
                          : item?.level == 10
                          ? '#2B8EF3'
                          : item?.level == 11
                          ? '#e05861'
                          : item?.level == 6
                          ? '#fed36a'
                          : '#6fe3ba',
                      borderColor: 'transparent',
                    }"
                    :color="
                      item?.level == 9
                        ? 'rgba(255, 255, 255, 0.26)'
                        : item?.level == 10
                        ? 'rgba(43, 142, 243,0.3)'
                        : item?.level == 11
                        ? 'rgba(245, 108, 108,0.3)'
                        : item?.level == 6
                        ? 'rgba(254, 211, 106, 0.26)'
                        : ''
                    "
                  >
                    {{
                      item?.level == 9
                        ? '离线'
                        : item?.level == 10
                        ? '高报'
                        : item?.level == 11
                        ? '低报'
                        : item?.level == 6
                        ? '故障'
                        : ''
                    }}
                  </el-tag>
                </div>
              </div>
              <div class="imgs">
                <img src="../assets/image/klt.png" alt="" />
              </div>
              <div class="warnB">
                <el-descriptions direction="vertical" :column="2" :colon="false">
                  <el-descriptions-item label="气体类型">{{
                    item?.type == 'oxygen' ? '氧气' : '可燃气 '
                  }}</el-descriptions-item>
                  <el-descriptions-item label="当前浓度值">
                    <span v-if="item?.level == 9">- -</span>
                    <span v-else>{{ item?.concentration || 0 }}</span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
            <div class="right">
              <div class="Info">
                <el-descriptions title="报警信息" direction="vertical" :column="2" :colon="false">
                  <el-descriptions-item label="报警类型"
                    >{{
                      item?.level == 9
                        ? '离线'
                        : item?.level == 10
                        ? '高报'
                        : item?.level == 11
                        ? '低报'
                        : item?.level == 6
                        ? '故障'
                        : ''
                    }}
                  </el-descriptions-item>
                  <el-descriptions-item label="报警浓度值">
                    <span v-if="item?.level == 9">- -</span>
                    <span v-else>{{ item?.e_data || 0 }}</span>
                  </el-descriptions-item>

                  <el-descriptions-item label="报警时间">
                    {{ item?.createdDate || '- -' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="恢复时间">
                    {{ item?.restoreDate || '- -' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="响应时间">
                    {{ item?.responseDate || '- -' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="响应人">
                    {{ item?.responder || '- -' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="所属企业" :span="2">
                    {{ item?.project_name || '- -' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="地址" :span="2">{{ item?.location || '- -' }}</el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </div>
          <div class="responseBtn">
            <el-button class="searchBtn" style="color: #94ceff" @click="ok(item)">响应</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { initWebSocket, closeWebSocket } from '@/utils/warnSocket'
import Warn from '@/utils/warn'
import { reactive, ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  switch: {
    type: Boolean,
    default: true,
  },
})

// 子类暴露属性，方便父类调用
defineExpose({
  initWs,
  closeWebSocket,
})

const audioRef = ref(null)
const audioSource = ref()

const playAudio = () => {
  if (!warnList.value.length) {
    audioSource.value = ''
  } else {
    nextTick(() => {
      // audioRef.value.pause()
      audioSource.value = require('../assets/warnMusic.mp3')
      // audioRef.value.play()
      audioRef.value?.play().catch(err => {
        console.log(err)
      })
    })
  }
}

const pauseAudio = () => {
  audioRef.value.pause()
}
const warnList = ref([])
const audio = ref(null)
// 连接ws
function initWs() {
  let userData = JSON.parse(localStorage.getItem('USERDATA'))
  let id = userData.project_id ? userData.project_id : 'all'
  let currentTime = new Date().getTime()
  // let wsUrl
  // if (process.env.NODE_ENV == 'development') {
  //   wsUrl = `ws://124.222.80.28:8086/klt/${id}/${currentTime}`
  //   // wsUrl = `ws://192.168.1.187:8086/klt/${id}/${currentTime}` //唐哥本地
  // } else {
  //   wsUrl = `ws://120.25.122.94:5000/klt/${id}/${currentTime}`
  // }
  let wsUrl = `${process.env.VUE_APP_WS_URL}/klt/${id}/${currentTime}`
  let params = {
    action: 1,
    params: {
      projectId: `klt/${id}/${currentTime}`,
    },
  }
  initWebSocket(wsUrl, params)
}

function add() {
  let num = new Date().getTime()
  warnList.value.unshift({
    _id: num,
    level: 9,
    deviceId: `测试${num}`,
    device_name: '恭喜发财',
  })
  //   最新时间排序
  warnList.value.sort((a, b) => b._id - a._id)
  playAudio()
}
function del(id) {
  warnList.value = warnList.value.filter(e => e._id !== id)
}

function close() {
  warnList.value.splice(0, 1)
  if (!warnList.value.length) {
    pauseAudio()
  }
}
function clear() {
  warnList.value = []
  pauseAudio()
}
async function ok(item) {
  try {
    let res = await Warn.responseOk(item._id)
    if (res.error_code == 0) {
      warnList.value.splice(0, 1)
      ElMessage({
        message: `${item.deviceId}响应成功`,
        type: 'success',
      })
      pauseAudio()
    }
  } catch (error) {
    ElMessage({
      message: error.msg,
      type: 'error',
    })
  }
}
function removeDuplicatesByDeviceId(arr) {
  const deviceIdMap = new Map()
  arr.forEach(item => {
    const _id = item._id
    if (!deviceIdMap.has(_id) || item.createdDate > deviceIdMap.get(_id).createdDate) {
      deviceIdMap.set(_id, item)
    }
  })

  // const deduplicatedArray = Array.from(deviceIdMap.values()).sort((a, b) => b.createdDate - a.createdDate)
  const deduplicatedArray = Array.from(deviceIdMap.values())
  return deduplicatedArray
}

onMounted(() => {
  playAudio()
  window.addEventListener('WarnOnmessage', event => {
    // 在这里处理接收到的数据 data
    let data = event.detail.data
    // console.log(event.detail, '原有data.warning')
    if (data.warning) {
      warnList.value.unshift(data.warning)
      // 整理重复数据排序
      let newArr = removeDuplicatesByDeviceId(warnList.value)
      warnList.value = newArr
      console.log(warnList.value, 'warnList.value')

      playAudio()
    }
  })
})
</script>
<style lang="scss" scoped>
#warnDialog {
  .warnMask {
    width: 100%;
    height: 100%;
    position: absolute;
    background: #000;
    opacity: 0.5;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
  }
  width: 100%;
  overflow-y: scroll;
  box-sizing: border-box;
  .dialogBox {
    .dialog {
      z-index: 999999;
      overflow-y: scroll;
      // max-height: 600px;
      box-sizing: border-box;
      .bj1 {
        background: url('@/assets/image/digBg.png') no-repeat;
      }
      .bj2 {
        background: url('@/assets/image/digBg2.png') no-repeat;
      }
      :deep(.warnBox) {
        padding: 85px 100px 50px 95px;
        width: var(--W);
        border-radius: 15px;
        box-sizing: border-box;
        position: absolute;
        left: 50%;
        top: var(--T);
        transform: translate(-50%, -50%);
        z-index: var(--Z);
        transition: 0.2s linear;
        background-size: 100% 100%;
        .header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          .text {
            background: url('@/assets/image/digTitleBg.png');
            background-size: 100% 100%;
            width: 20%;
            // width: 215px;
            height: 50px;
            line-height: 57px;
            position: absolute;
            left: 50%;
            top: -10px;
            transform: translateX(-50%);
            z-index: 999999999999999;

            div {
              font-size: 24px;
              font-weight: 700;
              letter-spacing: 0px;
              background: linear-gradient(180deg, rgba(5, 156, 255, 1) 37%, rgba(51, 248, 242, 1) 100%);
              line-height: 50px;
              -webkit-background-clip: text;
              color: transparent;
            }
          }
          .close {
            position: absolute;
            right: 30px;
            top: 35px;
            display: flex;
            align-items: center;
            img {
              width: 35px;
              height: 35px;
              cursor: pointer;
              display: block;
            }
            .clear {
              color: #42bded;
              font-size: 16px;
              width: 100%;
              margin-right: 20px;
              cursor: pointer;
              text-decoration: underline;
            }
          }
        }
        .ctn {
          display: flex;
          justify-content: space-between;
          min-height: 380px;
          .left {
            width: 35%;
            min-height: 380px;

            .deviceId {
              height: 48px;
              line-height: 48px;
              text-align: center;
              background: linear-gradient(
                90deg,
                rgba(5, 156, 255, 0) 0%,
                rgba(5, 156, 255, 0.35) 26.58%,
                rgba(5, 156, 255, 0.35) 77.48%,
                rgba(5, 156, 255, 0) 100%
              );
              div {
                background: linear-gradient(180deg, rgba(164, 226, 255, 1) 0%, rgba(20, 182, 255, 1) 100%);
                -webkit-background-clip: text;
                color: transparent;
                font-size: 18px;
                line-height: 48px;
                font-weight: 700;
              }
            }
            .deviceName {
              display: flex;
              align-items: center;
              justify-content: center;
              margin-top: 20px;
              .name {
                font-size: 14px;
                font-weight: 400;
                color: #94ceff;
                margin-right: 10px;
              }
            }
            .name {
              font-size: 14px;
              font-weight: 700;
              letter-spacing: 0px;
              line-height: 21px;
              color: rgba(148, 206, 255, 1);
              text-align: left;
              vertical-align: top;
            }
            .imgs {
              padding: 25px 30px;
              box-sizing: border-box;
              img {
                width: 210px;
                height: 187px;
              }
            }
            .warnB {
              padding-left: 45px;
              box-sizing: border-box;
              overflow: hidden;
              .el-descriptions__body {
                background: transparent;
                tr {
                  th {
                    color: #94ceff;
                  }
                }
                td {
                  color: #fff;
                }
              }
              .el-descriptions-item__cell {
                padding-bottom: 0;
              }
              .el-descriptions-item__content {
                padding-bottom: 15px;
                font-size: 16px;
              }
            }
          }
          .right {
            width: 60%;
            flex: 1;
            margin-left: 50px;
            .Info {
              background: url('@/assets/image/infoBg.png') no-repeat;
              background-size: 100% 100%;
              background-position: center;
              padding: 20px 30px;
              box-sizing: border-box;
              .el-descriptions__title {
                font-size: 18px;
                font-weight: 700;
                background: linear-gradient(180deg, rgba(5, 156, 255, 1) 37%, rgba(51, 248, 242, 1) 100%);

                -webkit-background-clip: text;
                color: transparent;
              }
              .el-descriptions__body {
                background: transparent;
                tr {
                  th {
                    color: #94ceff;
                  }
                }
                td {
                  color: #fff;
                }
              }
              .el-descriptions-item__cell {
                padding-bottom: 0;
              }
              .el-descriptions-item__content {
                padding-bottom: 15px;
                font-size: 16px;
              }
            }
          }
        }
        .responseBtn {
          padding-top: 35px;
          .el-button {
            width: 167px;
            height: 53px;
            border: none;
            background: rgba(4, 26, 59, 1);
            box-shadow: inset 0px 0px 30px 10px rgba(13, 155, 255, 1);
          }
        }
      }
    }
  }
}
</style>

